package com.c.ctgproject.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.ApplicationInfo
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Environment
import android.text.Editable
import android.text.TextWatcher
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.jpush.android.api.JPushInterface
import com.c.ctgproject.R
import com.c.ctgproject.base.*
import com.c.ctgproject.customview.GlideImageLoader
import com.c.ctgproject.customview.ImagePickerLoader
import com.c.ctgproject.entity.MenusEntity
import com.c.ctgproject.entity.MenusUseEntity
import com.c.ctgproject.entity.ResultEntity
import com.c.ctgproject.mode.MyConstants
import com.c.ctgproject.mode.UserMenuEnum
import com.c.ctgproject.ui.login.CharactersChangeActivity
import com.c.ctgproject.ui.other.SettingActivity
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonDeserializer
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImagePickType
import com.lwkandroid.widget.ninegridview.NineGirdImageContainer
import com.lwkandroid.widget.ninegridview.NineGridBean
import com.lwkandroid.widget.ninegridview.NineGridView
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.yzq.zxinglibrary.android.CaptureActivity
import kotlinx.android.synthetic.main.item_setting_layout.view.*
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.jetbrains.anko.startActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.*
import java.lang.StringBuilder
import java.lang.reflect.Method
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import android.graphics.Bitmap
import android.provider.MediaStore
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.recyclerview.widget.RecyclerView
import com.c.ctgproject.entity.file.CommonFileResultEntity
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.wiget.dialog.LoadingDialog
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import okhttp3.MultipartBody
import org.jetbrains.anko.imageResource
import java.math.BigDecimal


var userToken = ""
var currentAlias = 0
var currentSet = HashSet<String>()
var companyId = 0
var userId = 0

//二维码扫描回调码
const val QR_CODE_RESULT = 1000

object BoWenUtils {
    /**
     * 判断是否为DEBUG模式
     * @return true即为DEBUG模式
     */
    fun isDEBUG(): Boolean {
        val info = CTGproject.getBaseApplication().applicationInfo
        return (info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0)
    }

    /*** 获取颜色*/
//    fun getColor(context: Context, color: Int): Int {
//        return ContextCompat.getColor(context, color)
//    }
}

/**
 * 扫描二维码
 */
fun AppCompatActivity.scanQr() {
    val intent = Intent(this, CaptureActivity::class.java)
    startActivityForResult(intent, QR_CODE_RESULT)
}
inline fun <reified T>Gson.fromString(data:String):T{
    return fromJson(data,T::class.java)
}
inline fun <reified T:ViewModel>setViewModel(owner: ViewModelStoreOwner):T{
    return ViewModelProvider(owner)[T::class.java]
}

/*** dp转PX*/
fun Float.toPx(context: Context): Int {
    val scale = context.resources.displayMetrics.density
    return (this * scale + 0.5f).toInt()
}

/**切换item隐藏展示状态*/
fun ImageView.handlerArrow(show: Boolean, view: View? = null) {
    imageResource = if (show) R.drawable.ic_arrow_grey_up else R.drawable.ic_arrow_grey_down
    view?.let {
        it.visibility = if (show) View.VISIBLE else View.GONE
    }
}


const val sharedName = "ShareData"

val sp: SharedPreferences by lazy {
    MyBaseApplication.getContext().getSharedPreferences(sharedName, Context.MODE_PRIVATE)
}


/*** 将数据保存到SharedPreference*/
fun Any.sharedSave(key: String) {
    when (this.javaClass.simpleName) {
        "String" -> sp.edit().putString(key, this as String).apply()
        "Integer" -> sp.edit().putInt(key, this as Int).apply()
        "Boolean" -> sp.edit().putBoolean(key, this as Boolean).apply()
        "Float" -> sp.edit().putFloat(key, this as Float).apply()
        "Long" -> sp.edit().putLong(key, this as Long).apply()
        else -> sp.edit().putString(key, this.toString()).apply()
    }
}

/*** 从SharedPreference中取值*/
fun sharedGet(key: String, def: Any): Any {
    return when (def.javaClass.simpleName) {
        "String" -> sp.getString(key, def as String)!!
        "Integer" -> sp.getInt(key, def as Int)
        "Boolean" -> sp.getBoolean(key, def as Boolean)
        "Long" -> sp.getLong(key, def as Long)
        "Float" -> sp.getFloat(key, def as Float)
        else -> sp.getString(key, "")!!
    }
}

/*** 保存数据到SharedPreference*/
fun sharedSave(save: SharedPreferences.Editor.() -> Unit) {
    val editor = sp.edit()
    editor.save()
    editor.apply()
}


/*** 页面跳转 不传值*/
inline fun <reified T : Activity> AppCompatActivity.startActivity() {
    startActivity(Intent(this, T::class.java))
}


/*** 监听EditText输入框变化*/
fun EditText.handlerText(handlerText: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
            handlerText.invoke(p0.toString())
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }
    })
}


/*** key和value 封装到RequestBody中*/
fun handlerBody(vararg pair: Pair<String, Any>): RequestBody {
    val map: MutableMap<String, Any> = HashMap()
    pair.forEach {
        map[it.first] = it.second
    }
    val obj = Gson().toJson(map)
    return RequestBody.create(
        MediaType.parse("application/json; charset=utf-8"),
        obj
    )
}


fun handlerBody(map: Map<String, Any?>): RequestBody {
    return RequestBody.create(
        MediaType.parse("application/json; charset=utf-8"),
        Gson().toJson(map)
    )
}
private var lastClickTime: Long = 0
fun isFastDoubleClick(): Boolean {
    val time = System.currentTimeMillis()
    if (time - lastClickTime < 500) {
        return true
    }
    lastClickTime = time
    return false
}
/***将实体类封装到body中*/
fun handlerBodyEntity(any: Any): RequestBody {
    return RequestBody.create(
        MediaType.parse("application/json; charset=utf-8"),
        getGson().toJson(any)
    )
}

/*** 设置和角色切换下拉框*/
//@SuppressLint("InflateParams")
fun BaseActivity.showPopupWindow(view: View) {
//    val mView = View.inflate(this, R.layout.item_setting_layout, null)
    val mView = LayoutInflater.from(this).inflate(R.layout.item_setting_layout, null)
    val popupWindow = PopupWindow(
        mView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true
    )
    //设置背景透
    popupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    popupWindow.showAsDropDown(view)
    //设置
    mView.mSettingTV.setOnClickListener {
        startActivity<SettingActivity>()
    }
    //角色切换
    mView.mCharacterTV.setOnClickListener {
        //进行角色切换前清除上次选择的角色的ID
        "".sharedSave(MyConstants.CHARACTER_ID)
        startActivity<CharactersChangeActivity>(MyConstants.USER_INFO to sharedGet(MyConstants.USER_INFO, "") as String)
        finish()
    }
    mPopupWindow = popupWindow
}

/*** 设置和角色切换下拉框*/
@SuppressLint("InflateParams")
fun BaseActivityV2.showPopupWindow(view: View) {
    val mView = LayoutInflater.from(this).inflate(R.layout.item_setting_layout, null)
    val popupWindow = PopupWindow(
        mView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true
    )
    //设置背景透
    popupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    popupWindow.showAsDropDown(view)
    //设置
    mView.mSettingTV.setOnClickListener {
        startActivity<SettingActivity>()
    }
    //角色切换
    mView.mCharacterTV.setOnClickListener {
        //进行角色切换前清除上次选择的角色的ID
        "".sharedSave(MyConstants.CHARACTER_ID)
        startActivity<CharactersChangeActivity>(MyConstants.USER_INFO to sharedGet(MyConstants.USER_INFO, "") as String)
        finish()
    }
    mPopupWindow = popupWindow
}

/*** 根据角色跳转到响应的页面*/
fun AppCompatActivity.characterJump(name: String, menus: List<MenusEntity>? = null) {
    //根据用户权限进入相应的页面
    when (name) {
        //档案部
        UserMenuEnum.ARCHIVES_DEPT.menuName -> {
            handlerMenu(this, UserMenuEnum.ARCHIVES_DEPT, "档案部", menus)
        }
        //门卫
        UserMenuEnum.DOOR_GUARD.menuName -> {
            handlerMenu(this, UserMenuEnum.DOOR_GUARD, "门卫", menus)
        }
        //仓储
        UserMenuEnum.STORAGE_DEPT.menuName -> {
            handlerMenu(this, UserMenuEnum.STORAGE_DEPT, "仓储部", menus)
        }
        //销售部
        UserMenuEnum.SALES.menuName -> {
            handlerMenu(this, UserMenuEnum.SALES, "销售部", menus)
        }
        //生产
        UserMenuEnum.PRODUCTION.menuName -> {
            handlerMenu(this, UserMenuEnum.PRODUCTION, "生产", menus)
        }
        //审核
        UserMenuEnum.REVIEW.menuName -> {
            handlerMenu(this, UserMenuEnum.REVIEW, "审核", menus)
        }
        //客服
        UserMenuEnum.SERVICE.menuName -> {
            handlerMenu(this, UserMenuEnum.SERVICE, "审核", menus)
        }
        else -> {
            MyLog.d("该角色暂未开放")
            CustomToast.showToast(this, "该角色暂未开放")
        }
    }
}

private fun handlerMenu(context: Activity, enum: UserMenuEnum, characterName: String, menus: List<MenusEntity>?) {
    currentAlias = enum.alias
    val set = HashSet<String>()
    set.add(enum.menuName + "_" + companyId)
    currentSet = set
    JPushInterface.setTags(context, currentAlias, set)
    CTGproject.getBaseApplication().characterName = characterName
    val intent = Intent(context, enum.activity)
    intent.putExtra(MyConstants.MENUS, getGson().toJson(menus))
    context.startActivity(intent)
    context.finish()
}

var nowTime = 0L

/*** 退出APP*/
fun AppCompatActivity.exitApp() {
    val currentTime = System.currentTimeMillis()
    //两次点击间隔小于2秒可以退出
    if (currentTime - nowTime < 2000) {
        finish()
    } else {
        CustomToast.showToast(this, "再次点击退出")
    }
    nowTime = currentTime
}

/*** 设置EditText编辑框内容*/
fun setEditText(msg: String): Editable {
    return Editable.Factory.getInstance().newEditable(msg)
}

fun EditText.textSet(msg: String) {
    this.text = Editable.Factory.getInstance().newEditable(msg)
}

/*** 反射隐藏小键盘*/
fun EditText.unShowKeyBoard() {
    val cls = EditText::class.java
    var method: Method
    try {
        method = cls.getMethod("setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType)
        method.isAccessible = true
        method.invoke(this, false)
    } catch (e: Exception) {
    }
    try {
        method = cls.getMethod("setSoftInputShownOnFocus", Boolean::class.javaPrimitiveType)
        method.isAccessible = true
        method.invoke(this, false)
    } catch (e: Exception) {
    }
}

/**
 * 将接口回调信息格式化为字符串
 */
suspend fun Call<ResponseBody>.awaitSync(): String {
    return suspendCoroutine {
        enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                MyLog.d("携程onFailure:$t")
                if (t.message.toString() == "timeout") {
                    it.resumeWithException(RuntimeException("连接服务器超时,请稍后再试"))
                } else {
                    it.resumeWithException(RuntimeException(t.message.toString()))
                }
            }

            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                try {
                    val body = response.body()
                    body?.let { b ->
                        it.resume(b.string())
                    }
                    if (body == null) {
                        it.resumeWithException(RuntimeException("出现错误,请稍后再试"))
                    }

                } catch (e: Exception) {
                    it.resumeWithException(RuntimeException(e.message.toString()))
                    MyLog.d("携程Exception:${e.message}")
                }
            }
        })
    }
}

/**
 * 将接口回调信息格式化为统一的ResultEntity
 */
suspend fun <T> Call<T>.commonAwaitSync(): ResultEntity<*> {
    return suspendCoroutine {
        enqueue(object : Callback<T> {
            override fun onFailure(call: Call<T>, t: Throwable) {
                MyLog.d("携程onFailure:$t")
                if (t.message.toString() == "timeout") {
                    it.resumeWithException(RuntimeException("连接服务器超时,请稍后再试"))
                } else {
                    it.resumeWithException(RuntimeException(t.message.toString()))
                }
            }

            override fun onResponse(call: Call<T>, response: Response<T>) {
                try {
                    val body = response.body() as ResponseBody
                    val result = getGson().fromJson(body.string().toString(), ResultEntity::class.java)
                    it.resume(result)
                } catch (e: java.lang.Exception) {
                    it.resumeWithException(RuntimeException(e.message.toString()))
                    MyLog.d("携程Exception:${e.message}")
                }
            }
        })
    }
}


fun getGson(): Gson {
    val builder = GsonBuilder()
    builder.registerTypeAdapter(Date::class.java, JsonDeserializer<Any?> { json, _, _ -> Date(json.asJsonPrimitive.asLong) })
    return builder.serializeNulls().create()
}

/**
 * 将文件转为Base64
 */
fun file2Base64(file: File): String {
    var base64: String? = null
    var `in`: InputStream? = null
    try {
        `in` = FileInputStream(file)
        val bytes = ByteArray(`in`.available())
        val length: Int = `in`.read(bytes)
        base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT)
    } catch (e: FileNotFoundException) {
        MyLog.d(e.message.toString())
        e.printStackTrace()
    } catch (e: IOException) {
        MyLog.d(e.message.toString())
        e.printStackTrace()
    } finally {
        try {
            `in`?.close()
        } catch (e: IOException) {
            MyLog.d(e.message.toString())
            e.printStackTrace()
        }
    }
    return base64!!
}

/*** ViewModel携程*/
fun ViewModel.launch(block: suspend () -> Unit, error: suspend (Throwable) -> Unit) = viewModelScope.launch {
    try {
        block()
    } catch (e: Throwable) {
        error(e)
    }
}


/***ViewModel携程 处理错误*/
fun BaseViewModel.launch(block: suspend () -> Unit) = viewModelScope.launch {
    try {
        block()
    } catch (e: Throwable) {
        MyLog.d("携程出现问题:${e.message}")
        setError(e.message.toString())
    }
}


/**
 * 封装回调
 */
fun String.handlerCall(success: () -> Unit, error: (msg: String) -> Unit) {
    val data = initData(this)
    if (data.status == 0) {
        success()
    } else {
        error(data.msg.toString())
    }
}

/***处理网络请求回调*/
fun Context.handlerHttpResult(data: String, block: () -> Unit) {
    val entity = getGson().fromJson(data.replace(" ", ""), ResultEntity::class.java)
    if (entity.status == 1) {
        block()
    } else {
        showToast(entity.msg)
    }
}

/***封装处理回调 将data内容带回(广汽原先写的和其他项目不一致)*/
fun Context.handlerDataGQ(data: String, block: (data: Any?) -> Unit) {
    val result = getGson().fromJson(data, ResultEntity::class.java)
    if (result.status == 1) {
        block(result.data)
    } else {
        MyLog.d("异常:${result.msg}")
        showToast(result.msg)
    }
}
/***封装处理回调 将data内容带回*/
fun Context.handlerData(data: String, block: (data: Any?) -> Unit) {
    val result = getGson().fromJson(data, ResultEntity::class.java)
    if (result.status == 0) {
        block(result.data)
    } else {
        showToast(result.msg)
    }
}
/***封装处理回调 将data内容带回*/
fun Context.handlerDataZeroIsSuccess(data: String, block: (data: Any?) -> Unit) {
    val result = getGson().fromJson(data, ResultEntity::class.java)
    if (result.status == 0) {
        block(result.data)
    } else {
        MyLog.d("异常:${result.msg}")
        showToast(result.msg)
    }
}


/*** 格式化网络请求数据*/
fun initData(data: String):ResultEntity<*> {
    return getGson().fromJson(data.replace(" ", ""), ResultEntity::class.java)
}

fun Context.showToast(msg: Any?) {
    CustomToast.showToast(this, msg.toString())
}

fun Fragment.showToast(msg: Any) {
    CustomToast.showToast(requireContext(), msg.toString())
}

/**
 * spinner监听 返回点击位置
 */
fun Spinner.handlerSelect(handlerSelect: (Int) -> Unit) {
    onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }

        override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
            handlerSelect.invoke(position)
        }
    }
}

/***结束上啦加载和下拉刷新*/
fun SmartRefreshLayout.over() {
    finishRefresh()
    finishLoadMore()
}

/**
 * 处理null字符串
 */
fun Any?.handlerNull(): String {
    val data = this.toString()
    return if (data == "null" || data.isEmpty()) {
        ""
    } else {
        data
    }
}

fun Any?.noDataHandler(): String {
    val data = this.toString()
    return if (data == "null" || data.isEmpty()) {
        "暂无数据"
    } else {
        data
    }
}

fun Int?.finishHandler(): String {
    return when (this) {
        1 -> "已完成"
        0 -> "未完成"
        else -> "暂无数据"
    }
}


fun Context.getParentMenuCode(menuCode: String?): String {
    val sb = StringBuilder()
    val inputStream = assets.open("menusJson.json")
    BufferedReader(InputStreamReader(inputStream)).use {
        var line = ""
        while (true) {
            line = it.readLine() ?: break
            sb.append(line)
        }
    }
    val entity = getGson().fromJson(sb.toString(), MenusUseEntity::class.java)
    entity.data?.let {
        it.forEach { parent ->
            parent.childList?.forEach { child ->
                if (child.menuCode == menuCode) {
                    return parent.menuCode.handlerNull()
                }
            }
        }
    }
    return ""
}

/***通用Dialog*/
fun Context.commonDialog(msg: String, block: () -> Unit) {
    AlertDialog.Builder(this).setTitle(msg)
        .setPositiveButton("确认") { _, _ ->
            block()
        }.setNegativeButton("返回") { _, _ ->
        }.show()
}

fun NineGridView.init(context: FragmentActivity, imageShowList: ArrayList<String>, maxNum: Int, resultCode: Int, column: Int = 3) {
    //设置图片加载器，这个是必须的，不然图片无法显示
    setImageLoader(GlideImageLoader())
    //设置显示列数，默认3列
    setColumnCount(column)
    //设置是否为编辑模式，默认为false
    setIsEditMode(true)
    //设置单张图片显示时的尺寸，默认100dp
    setSingleImageSize(150)
    //设置单张图片显示时的宽高比，默认1.0f
    setSingleImageRatio(0.8f)
    //设置最大显示数量，默认9张
    setMaxNum(maxNum)
    //设置图片显示间隔大小，默认3dp
    setSpcaeSize(4)
    //设置删除图片
    //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
    //设置删除图片与父视图的大小比例，默认0.25f
    //设置删除图片
    //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
    //设置删除图片与父视图的大小比例，默认0.25f
    setRatioOfDeleteIcon(0.15f)
    //设置“+”号的图片
    setIcAddMoreResId(R.drawable.ic_ngv_add_pic)
    //设置各类点击监听
    setOnItemClickListener(object : NineGridView.onItemClickListener {
        override fun onNineGirdItemDeleted(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {
            if (imageShowList.isNotEmpty()) {
                imageShowList.removeAt(position)
            }
        }

        override fun onNineGirdItemClick(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {


        }

        override fun onNineGirdAddMoreClick(cha: Int) {
            //编辑模式下，图片展示数量尚未达到最大数量时，会显示一个“+”号，点击后回调这里
            ImagePicker()
                .cachePath(Environment.getExternalStorageDirectory().absolutePath)
                .pickType(ImagePickType.MULTI)
                .displayer(ImagePickerLoader())
                .maxNum(cha)
                .start(context, resultCode)
        }
    })
}

fun TabLayout.handlerSelectReturnText(block: (String) -> Unit) {
    this.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab) {
            block(tab.text.handlerNull())
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {

        }

        override fun onTabReselected(tab: TabLayout.Tab?) {

        }

    })
}

/**强转大写*/
fun EditText.handlerToUpperCase() {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {

        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            removeTextChangedListener(this)
            textSet(p0.toString().toUpperCase())
            setSelection(p0.toString().length)
            addTextChangedListener(this)
        }
    })
}


fun saveBitmapFile(context: Context, bitmap: Bitmap, index: Int): File {
    val file = File(context.getExternalFilesDir(null)?.absolutePath + index + ".jpg") //将要保存图片的路径
    try {
        val bos = BufferedOutputStream(FileOutputStream(file))
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
        bos.flush()
        bos.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return file
}
fun saveBitmapFile(context: Context, bitmap: Bitmap, index: Int,compress:Int=50): File {
    val file = File(context.getExternalFilesDir(null)?.absolutePath + index + ".jpg") //将要保存图片的路径
    try {
        val bos = BufferedOutputStream(FileOutputStream(file))
        bitmap.compress(Bitmap.CompressFormat.JPEG, compress, bos)
        bos.flush()
        bos.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return file
}
fun View.myShake() {
    YoYo.with(Techniques.Shake).duration(300)
        .repeat(0).playOn(this)
}

fun Context.upDataFile(loading: LoadingDialog, files: java.util.ArrayList<File>, block: (data: List<CommonFileResultEntity.DataBean>?) -> Unit) {
    val parts = java.util.ArrayList<MultipartBody.Part>()
    files.forEach { file ->
        val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val part = MultipartBody.Part.createFormData("file", file.name, requestFile)
        parts.add(part)
    }
    ApiMethods.apiSubscribe(ApiMethods.retrofit.commonFileUpload(parts), MyObserverHandlerLoading(this, loading) {
        MyLog.d("文件回调:$it")
        val data = getGson().fromJson(it, CommonFileResultEntity::class.java)
        block(data.data)
    })
}

fun handlerPassword(password: String): String {
    return Base64.encodeToString(password.toByteArray(), Base64.DEFAULT)
}

fun handlerStr2Base64(password: String): String {
    return Base64.encodeToString(password.toByteArray(), Base64.DEFAULT)
}

/***两数相乘保留后三位*/
fun handlerKwh(a: String, b: String): String? {
    if (a.isEmpty() || b.isEmpty()) return null
    val aValue = BigDecimal(a).setScale(3, BigDecimal.ROUND_DOWN)
    val bValue = BigDecimal(b).setScale(3, BigDecimal.ROUND_DOWN)
    MyLog.d("第一个数:${aValue} 第二个数${bValue}")
    var result = aValue.multiply(bValue)
    result = result.divide(BigDecimal("1000"))
    return result.setScale(3, BigDecimal.ROUND_HALF_UP).handlerNull()
}




fun EditText.handlerDecimal3(block: (String) -> Unit) {
    var s1 = ""
    val textWatcher = object : TextWatcher {

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            if (s.toString().contains(".")) {
                if (s.length - 1 - s.toString().indexOf(".") > 3) {
                    s1 = s.toString().subSequence(
                        0,
                        s.toString().indexOf(".") + 3 + 1
                    ).handlerNull()
                    textSet(s1)
                    setSelection(s1.length)
                }
            }
            if (s.toString().trim().substring(0) == ".") {
                s1 = "0" + s.handlerNull()
                textSet(s1)
                setSelection(2);
            }
            if (s.toString().startsWith("0") && s.toString().trim().length > 1) {
                if (s.toString().substring(1, 2) != ".") {
                    textSet(s.subSequence(0, 1).handlerNull())
                    setSelection(1)
                    return
                }
            }
        }

        override fun afterTextChanged(s: Editable?) {
            block(s.handlerNull())
        }

    }
    addTextChangedListener(textWatcher)
}

fun EditText.handlerDecimal3() {
    var s1 = ""
    val textWatcher = object : TextWatcher {

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            if (s.toString().contains(".")) {
                if (s.length - 1 - s.toString().indexOf(".") > 3) {
                    s1 = s.toString().subSequence(
                        0,
                        s.toString().indexOf(".") + 3 + 1
                    ).handlerNull()
                    textSet(s1)
                    setSelection(s1.length)
                }
            }
            if (s.toString().trim().substring(0) == ".") {
                s1 = "0" + s.handlerNull()
                textSet(s1)
                setSelection(2);
            }
            if (s.toString().startsWith("0") && s.toString().trim().length > 1) {
                if (s.toString().substring(1, 2) != ".") {
                    textSet(s.subSequence(0, 1).handlerNull())
                    setSelection(1)
                    return
                }
            }
        }

        override fun afterTextChanged(s: Editable?) {

        }

    }
    addTextChangedListener(textWatcher)
}

fun  RecyclerView.handlerPosition(page:Int){
    if (page==1){
        scrollToPosition(0)
    }
}

fun  View.visible(){
    visibility=View.VISIBLE
}
fun  View.gone(){
    visibility=View.GONE
}
